<template>
	<view @touchmove="onTouchMove"> <!-- 防止页面无法触发 onPageScroll -->
		<view style="height: 1000px; background: #f0f0f0;">请向下滚动</view>

		<!-- 目标 view -->
		<view :class="['target-view', { 'active': isActive }]">
			当我移动到这里时，我的背景色会逐渐改变！
		</view>

		<view style="height: 1000px;"></view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				isActive: false,
				targetInView: false,
				threshold: 100 // 元素距离顶部多少 px 时开始变化
			};
		},
		methods: {
			onTouchMove() {
				// 空函数，防止阻止 onPageScroll 触发
			},
			checkElementPosition() {
				const query = uni.createSelectorQuery().in(this);
				query.select('.target-view').boundingClientRect(res => {
					if (res) {
						const systemInfo = uni.getSystemInfoSync();
						const windowHeight = systemInfo.windowHeight;
						const windinfo = uni.getWindowInfo()
						const top = res.top;
						// 如果目标元素出现在视口上方一定范围内
						if (top <= windowHeight - this.threshold && !this.targetInView) {
							this.targetInView = true;
							this.isActive = true;
						} else if (top > windowHeight - this.threshold && this.targetInView) {
							this.targetInView = false;
							this.isActive = false;
						}
					}
				}).exec();
			}
		},
		onReady() {
			// 组件加载完成后检查一次
			this.checkElementPosition();
		},
		onPageScroll(e) {
			this.checkElementPosition();
		}
	};
	
</script>

<style scoped>
	.target-view {
		height: 100px;
		background-color: white;
		text-align: center;
		line-height: 100px;
		font-size: 16px;
		transition: background-color 0.5s ease;
	}

	.target-view.active {
		background-color: #4CAF50;
	}
</style>